package com.mornd.utils;

import com.mornd.entity.Menu;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mornd
 * @date 2021/1/7 - 1:19
 * 操作页面左侧菜单
 */
public class TreeMenuUtil {
    /**
     * 构建菜单层级关系
     * @param treeList 菜单集合
     * @param topId 初始节点pid
     * @return
     */
    public static List<Menu> toTree(List<Menu> treeList, Integer topId) {
        List<Menu> retList = new ArrayList<Menu>();
        for (Menu parent : treeList) {
            if (topId == parent.getPid()) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static Menu findChildren(Menu parent, List<Menu> treeList) {
        for (Menu child : treeList) {
            if (parent.getId() == child.getPid()) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<Menu>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
